package com.frxuexi.mynews.fragment

import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.alibaba.android.arouter.launcher.ARouter
import com.frxuexi.mynews.R
import com.frxuexi.mynews.activity.VideoAdapter
import com.frxuexi.mynews.databinding.FragmentVideoBinding
import com.frxuexi.mynews.intent.VideoIntent
import com.frxuexi.mynews.state.VideoState
import com.frxuexi.mynews.viewmodel.VideoViewModel
import com.tencent.mmkv.MMKV
import com.witmed.home.view.DpTools
import com.witmed.home.view.ScrollCalculatorHelper
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [VideoFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class VideoFragment : Fragment() {
    lateinit var db:FragmentVideoBinding
    lateinit var vm:VideoViewModel
    lateinit var videoAdapter: VideoAdapter
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        // Inflate the layout for this fragment
        db = FragmentVideoBinding.inflate(layoutInflater, container, false)
        vm=ViewModelProvider(this).get(VideoViewModel::class.java)

        videoAdapter= VideoAdapter(requireContext(), arrayListOf())

        val manager = LinearLayoutManager(requireContext())

        db.videoRv.apply {
            adapter=videoAdapter
            layoutManager=manager
        }

        videoAdapter.setOnItemClickListener(object :VideoAdapter.OnItemClickListener{
            override fun onClick(position: Int) {
                ARouter.getInstance().build("/app/VideoActivity").withString("url",videoAdapter.list[position].videourl).navigation()
            }

        })

        videoAdapter.setOnItemLongClickListener(object :VideoAdapter.OnItemLongClickListener{
            override fun onLongClick(position: Int) {
                //长按事件
            }

        })

        val dm = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getMetrics(dm)
        val helper = ScrollCalculatorHelper(R.id.video_vp,
            dm.heightPixels/2-DpTools.dip2px(requireContext(),180),
            dm.heightPixels/2+DpTools.dip2px(requireContext(),180))

        //仿Viewpager滑动翻页效果
        val snapHelper = PagerSnapHelper()
        snapHelper.attachToRecyclerView(db.videoRv)


        db.videoRv.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                helper.onScrollStateChanged(recyclerView,newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val firstVisibleItemPosition = manager.findFirstVisibleItemPosition()
                val lastVisibleItemPosition = manager.findLastVisibleItemPosition()
                helper.onScroll(recyclerView,firstVisibleItemPosition,lastVisibleItemPosition,1)
            }
        })

        lifecycleScope.launch {
            vm.videoState.collect{
                when(it){
                    is VideoState.onVideoSuccess->{
                        Log.i("===video",it.data.toString())
                        videoAdapter.addData(it.data)

                    }
                    is VideoState.onError->{

                    }

                    else -> {}
                }
            }
        }

        lifecycleScope.launch{
            vm.videoChannel.send(VideoIntent.getVideos(2))
        }

        return db.root
    }
}